package api

import (
	"FeedXmh/app/dao"
	"FeedXmh/hub"
	"FeedXmh/redis"
	"fmt"
	jwt "github.com/gogf/gf-jwt"
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/net/ghttp"
	"github.com/gogf/gf/util/gconv"
	"paco_toolkit/DMXFGW"
)

var Status_his = status_his{}

type status_his struct {
}

func (a *status_his) Get(r *ghttp.Request) {
	res := g.Map{
		"code": 0,
		"msg":  "",
		"data": nil,
	}

	params := r.GetQueryMap()

	order := r.GetString("order")

	sn := gconv.String(params["sn"])
	addr := gconv.String(params["addr"])
	begin := gconv.String(params["begin"])
	end := gconv.String(params["end"])
	his_date := gconv.String(params["his_date"])
	farmid := gconv.String(params["farmid"])
	houseid := gconv.String(params["houseid"])

	mode := gconv.String(params["mode"])
	day := gconv.String(params["day"])
	online := gconv.String(params["online"])
	pig_num := gconv.String(params["pig_num"])
	health := gconv.String(params["health"])

	//fields := gconv.String(params["fields"])

	where := " 1=1 "

	if addr != "" {
		where += " and addr='" + addr + "'"
	}
	if sn != "" {
		where += " and sn='" + sn + "'"
	}

	if begin != "" {
		where += fmt.Sprintf(" and his_date>='%s' ", begin)
	}
	if end != "" {
		where += fmt.Sprintf(" and his_date<'%s' ", end)
	}
	if his_date != "" {
		where += fmt.Sprintf(" and his_date='%s' ", his_date)
	}
	if houseid != "" {
		where += fmt.Sprintf(" and addr in (SELECT device_addr AS addr FROM t_device WHERE houseid=%s)   ", houseid)
	}
	if farmid != "" {
		where += fmt.Sprintf(" and addr in (SELECT device_addr AS addr FROM t_device WHERE houseid in (SELECT id as houseid FROM t_house WHERE farmid=%s))   ", farmid)
	}

	if mode != "" {
		where += " and mode in (" + mode + ") "
	}
	if day != "" {
		where += " and day='" + day + "'"
	}
	if online != "" {
		online += " and online='" + online + "'"
	}
	if pig_num != "" {
		pig_num += " and pig_num='" + pig_num + "'"
	}
	if health != "" {
		health += " and health='" + health + "'"
	}

	claims := jwt.ExtractClaims(r)
	userid := claims["userid"].(string)
	url := r.URL.Path
	if dao.CheckApiPermission(url, r.Method, userid) {
		//管理员可以看到全部，其他角色按照权限获取
		if dao.IsAdmin(userid) || dao.IsService(userid) {

		} else {
			//where += fmt.Sprintf(" and addr in (SELECT device_addr FROM t_user_device WHERE userid='%s')",userid)
		}

		db := g.DB(g.Cfg().GetString("custom.db_name"))

		model := db.Model("t_hzfgw_node_status_his")
		//if fields != "" {
		//	model = model.Fields(fields)
		//}
		if order != "" {
			model = model.Order(order)
		} else {
			model = model.Order(" his_date desc ")
		}
		records, error := model.Where(where).All()
		if error != nil {
			g.Log().Line().Error(error)
			res["msg"] = error.Error()
			res["code"] = -1
		} else {
			list := records.List()

			for k, item := range list {
				addr := gconv.String(item["addr"])
				sn := gconv.String(item["sn"])
				//g.Log().Line(true).Debugf("status his:addr=%s,sn=%s", addr, sn)
				//采食量达标
				list[k]["health"] = ""
				mode := gconv.Int(item["mode"])
				_model := gconv.String(item["model"])
				day := gconv.Int(item["day"])
				pig_num := gconv.Int(item["pig_num"])
				if pig_num == 0 {
					if mode == DMXFGW.FEED_MODE_PG || mode == DMXFGW.FEED_MODE_LACTATION {
						pig_num = 1
					} else if mode == DMXFGW.FEED_MODE_NURSE || mode == DMXFGW.FEED_MODE_FAT {
						//使用当前猪只
						pig_num = gconv.Int(redis.GetGwNodePigNum(addr, sn))
					}
				}
				if pig_num == 0 {
					pig_num, _ = dao.T_hzfgw_node_para.GetPigNum(addr, sn)
				}
				day_use_feed_auto := gconv.Float32(item["day_use_feed_auto"])
				day_use_feed_man := gconv.Float32(item["day_use_feed_man"])
				day_use_feed := day_use_feed_man + day_use_feed_auto
				var avg_day_use_feed float32
				if pig_num > 0 {
					avg_day_use_feed = day_use_feed / float32(pig_num)
				}

				list[k]["day_use_feed"] = day_use_feed
				list[k]["avg_day_use_feed"] = avg_day_use_feed

				var health string
				var low, standard, high float32
				low, standard, high = hub.GetStandard(_model, mode, day)
				if low <= avg_day_use_feed && avg_day_use_feed <= high {
					//正常采食
					health = "good"
				} else {
					if low > avg_day_use_feed {
						//低采食
						health = "low"
					} else if high < avg_day_use_feed {
						//高采食
						health = "high"
					}
				}
				list[k]["low_standard"] = low
				list[k]["high_standard"] = high
				list[k]["standard"] = standard
				list[k]["health"] = health
			}

			res["code"] = 0
			res["data"] = list
		}
	} else {
		res["code"] = -1
		res["msg"] = "您没有该操作权限"
	}

	r.Response.WriteJson(res)
	r.ExitAll()
}
